import { BaseCanvas } from '../base/baseCanvas';
interface MapObject {
    x: number;
    y: number;
    [key: string]: any;
}

export class ClockTimer extends BaseCanvas {

    options: MapObject;

    constructor(canvasEle: HTMLCanvasElement, options: MapObject) {

        super(canvasEle);
        this.options = options;
        this.ctx.translate(options.x, options.y);
        this.ctx.save();
        this.initClock();

    }

    initClock() {
        this.drawOuterCircle();
        this.drawTimeMasks();
        this.timeTicker();
        window.requestAnimationFrame(() => {
            this.ctx.clearRect(-150, -150, 300, 300);
            this.initClock();
        });
    }

    timeTicker() {
        const currentTime = new Date();
        const currentHour = (currentTime.getHours() % 24) * 60 / 12;
        const currentMinute = currentTime.getMinutes();
        const currentSecond = currentTime.getSeconds();
        const getAngle = (timer: number) => {
            return (Math.PI * 2 * timer) / 60;
        };
        this.drawMinutePointer(40, getAngle(currentHour));
        this.drawMinutePointer(50, getAngle(currentMinute));
        this.drawSecond(60, getAngle(currentSecond));
    }

    drawOuterCircle() {
        const ctx = this.ctx;
        ctx.beginPath();
        ctx.strokeStyle = '#000';
        ctx.arc(0, 0, 79, 0, 2 * Math.PI);
        ctx.stroke();
        ctx.beginPath();
        ctx.strokeStyle = '#09f';
        ctx.lineWidth = 3;
        ctx.stroke();
        ctx.restore();
    }

    drawTimeMasks() {
        const ctx = this.ctx;
        ctx.lineWidth = 2;
        for (let i = 0; i < 60; i++) {
            ctx.beginPath();
            const lineLength = i % 5 === 0 ? -65 : -70;
            ctx.moveTo(-75, 0);
            ctx.lineTo(lineLength, 0);
            ctx.stroke();
            ctx.rotate(Math.PI / 30);
        }
        ctx.restore();
    }

    drawMinutePointer(length: number, rotate: number) {
        const ctx = this.ctx;
        ctx.beginPath();
        ctx.rotate(rotate);
        ctx.moveTo(0, 5);
        ctx.lineTo(0, -length);
        ctx.lineWidth = 4;
        ctx.lineCap = 'round';
        ctx.rotate(-rotate);
        ctx.stroke();
        ctx.restore();
    }

    drawSecond(length: number, rotate: number) {
        const ctx = this.ctx;
        ctx.beginPath();
        ctx.rotate(rotate);
        ctx.strokeStyle = '#D40000';
        ctx.moveTo(0, 5);
        ctx.lineTo(0, -length);
        ctx.lineWidth = 2;
        ctx.stroke();
        ctx.beginPath();
        ctx.arc(0, 10 - length, 4, 0, 2 * Math.PI);
        ctx.fillStyle = '#fff';
        ctx.fill();
        ctx.stroke();

        ctx.beginPath();
        ctx.fillStyle = '#D40000';
        ctx.arc(0, 0, 4, 0, 2 * Math.PI);
        ctx.fill();
        ctx.rotate(-rotate);
        ctx.restore();
    }
}
